package com.meirengu.webview.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.meirengu.common.StatusCode;
import com.meirengu.model.Result;
import com.meirengu.utils.DateUtils;
import com.meirengu.utils.HttpUtil;
import com.meirengu.webview.model.LmUser;
import com.meirengu.webview.model.LmUserBase;
import com.meirengu.webview.model.User;
import com.meirengu.webview.model.UserInfo;
import com.meirengu.webview.service.*;
import com.meirengu.webview.utils.ConfigUtil;
import com.meirengu.webview.utils.JudgeOperator;
import com.meirengu.webview.utils.MailUtil;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * ${DESCRIPTION}
 *
 * @author Mao
 * @create 2017-12-19 12:27
 */
@Controller
@RequestMapping("schedule")
public class ScheduleController extends BaseController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private UserService userService;
    @Autowired
    private KwOperationLogService kwOperationLogService;
    @Autowired
    private KwCcicFilterService kwCcicFilterService;
    @Autowired
    private KwPpdFilterService kwPpdFilterService;
    @Autowired
    CheckCodeService checkCodeService;
    @Autowired
    private KwInterfaceConfigService kwInterfaceConfigService;
    @Autowired
    private AsyncService asyncService;
    @Autowired
    private ScheduleService scheduleService;
    @Autowired
    private LmUserBaseService lmUserBaseService;
    @Autowired
    private LmUserService lmUserService;
    @Autowired
    private KwStatisticInterfaceService kwStatisticInterfaceService;

    Logger logger = LoggerFactory.getLogger(ScheduleController.class);

    /**
     * 定时发送大地保险数据
     */
    @ResponseBody
    @RequestMapping("/sendCcic")
    public Result sendCcic() {
        try {
            //查询当日记录
            Date currentDate = new Date();
            //当天开始时间
            Date dayBeginTime = DateUtils.getDayBeginTime(currentDate);
            //当天结束时间
            Date dayEndTime = DateUtils.getDayEndTime(currentDate);
            Date createTimeBegin = org.apache.commons.lang3.time.DateUtils.addDays(dayBeginTime, -1);
            Date createTimeEnd = org.apache.commons.lang3.time.DateUtils.addDays(dayEndTime, -1);
            //查出符合条件的用户
            Map<String, Object> map = new HashMap<>();
            map.put("createTimeBegin", createTimeBegin);
            map.put("createTimeEnd", createTimeEnd);
            List<Map<String, Object>> userList = userService.getList(map);
            kwOperationLogService.addOperationLog("1", " 推送渠道", "sendCcic",
                    "定时发送大地保险数据", DateUtils.dateToStr(createTimeBegin), DateUtils.dateToStr(createTimeEnd), "kw_user", userList.size(),
                    null, null, null);
            if (userList != null && userList.size() > 0) {
                for (Map<String, Object> userMap : userList) {
                    String id = userMap.get("id").toString();
                    if (userMap.get("name") != null) {
                        UserInfo userInfo = userInfoService.getByUserId(id);
                        if (userInfo != null && StringUtils.isNotBlank(userInfo.getId())) {
                            User user = new User();
                            user.setId(id);
                            user.setName(userMap.get("name").toString());
                            user.setMobile(userMap.get("mobile").toString());
                            user.setSex(Integer.parseInt(userMap.get("sex").toString()));
                            //获取上一天时间
                            long timemillis = DateUtils.getYesRanTime();
                            userInfo.setCreateDate(new Date(timemillis));
                            kwCcicFilterService.sendCCIC(userInfo, user);
                        }
                    }

                }
            }
            return super.setResult(StatusCode.OK, "", StatusCode.codeMsgMap.get(StatusCode.OK));
        } catch (Exception e) {
            e.printStackTrace();
            String params = String.format("参数：error:%s",
                    "定时发送大地保险数据接口报错");
            logger.error(">> ScheduleController.sendPpd throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            return super.setResult(StatusCode.INTERNAL_SERVER_ERROR, "", StatusCode.codeMsgMap.get(StatusCode.INTERNAL_SERVER_ERROR));
        }
    }


    /**
     * 定时发送拍拍贷接口
     */
    @ResponseBody
    @RequestMapping("/sendPpd")
    public Result sendPpd() {
        try {
            //查询当日记录
            Date currentDate = new Date();
            //当天开始时间
            Date dayBeginTime = DateUtils.getDayBeginTime(currentDate);
            //当天结束时间
            Date dayEndTime = DateUtils.getDayEndTime(currentDate);
            Date createTimeBegin = org.apache.commons.lang3.time.DateUtils.addDays(dayBeginTime, -3);
            Date createTimeEnd = org.apache.commons.lang3.time.DateUtils.addDays(dayEndTime, -3);
            //查出符合条件的用户
            Map<String, Object> map = new HashMap<>();
            map.put("createTimeBegin", createTimeBegin);
            map.put("createTimeEnd", createTimeEnd);
            List<Map<String, Object>> userList = userService.getList(map);
            kwOperationLogService.addOperationLog("1", " 推送渠道", "sendPpd",
                    "定时发送拍拍贷数据", DateUtils.dateToStr(createTimeBegin), DateUtils.dateToStr(createTimeEnd), "kw_user", userList.size(),
                    null, null, null);
            if (userList != null && userList.size() > 0) {
                for (Map<String, Object> userMap : userList) {
                    String id = userMap.get("id").toString();
                    if (userMap.get("name") != null) {
                        UserInfo userInfo = userInfoService.getByUserId(id);
                        if (userInfo != null && StringUtils.isNotBlank(userInfo.getId()) && StringUtils.isNotBlank(userInfo.getIdCard())) {
                            User user = new User();
                            user.setId(id);
                            user.setName(userMap.get("name").toString());
                            user.setMobile(userMap.get("mobile").toString());
                            user.setSex(Integer.parseInt(userMap.get("sex").toString()));
                            kwPpdFilterService.sendPpdai(userInfo, user);
                        }
                    }

                }
            }
            return super.setResult(StatusCode.OK, "", StatusCode.codeMsgMap.get(StatusCode.OK));
        } catch (Exception e) {
            e.printStackTrace();
            String params = String.format("参数：error:%s",
                    "定时发送拍拍贷接口报错");
            logger.error(">> ScheduleController.sendPpd throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            return super.setResult(StatusCode.INTERNAL_SERVER_ERROR, "", StatusCode.codeMsgMap.get(StatusCode.INTERNAL_SERVER_ERROR));
        }
    }


    /**
     * 定时新旦保险2保险数据
     */
    @ResponseBody
    @RequestMapping("/sendXbb2")
    public Result sendXbb2() {
        try {
            asyncService.sendXbb2();
        } catch (Exception e) {
            e.printStackTrace();
            String params = String.format("参数：error:%s",
                    "定时新旦保险2保险数据错误");
            logger.error(">> ScheduleController.sendXbb2 throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            return super.setResult(StatusCode.INTERNAL_SERVER_ERROR, "", null);
        }
        return super.setResult(StatusCode.OK, "", StatusCode.codeMsgMap.get(StatusCode.OK));
    }

    /**
     * 定时发送东方融资网数据
     */
    @ResponseBody
    @RequestMapping("/sendDfrz")
    public Result sendDfrz() {
        try {
            asyncService.sendDfrz();
        } catch (Exception e) {
            e.printStackTrace();
            String params = String.format("参数：error:%s",
                    "定时东方融资网数据错误");
            logger.error(">> ScheduleController.sendDfrz throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            return super.setResult(StatusCode.INTERNAL_SERVER_ERROR, "", null);
        }
        return super.setResult(StatusCode.OK, "", StatusCode.codeMsgMap.get(StatusCode.OK));
    }

    /**
     * 定时畅愿保险数据
     */
    @ResponseBody
    @RequestMapping("/sendCyis")
    public Result sendCyis(@RequestParam(value = "delayDays", defaultValue = "5") Integer delayDays) {
        try {
            asyncService.sendCyis(delayDays);
        } catch (Exception e) {
            e.printStackTrace();
            String params = String.format("参数：error:%s",
                    "定时畅愿保险数据错误");
            logger.error(">> ScheduleController.sendCyis throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            return super.setResult(StatusCode.INTERNAL_SERVER_ERROR, "", null);
        }
        return super.setResult(StatusCode.OK, "", StatusCode.codeMsgMap.get(StatusCode.OK));
    }

    /**
     * 定时发送新旦保险3数据
     */
    @ResponseBody
    @RequestMapping("/sendXbb3")
    public Result sendXbb3(@RequestParam(value = "amount", required = true) int amount) {
        try {
            asyncService.sendXbb3(amount);
        } catch (Exception e) {
            e.printStackTrace();
            String params = String.format("参数：error:%s",
                    "定时发送新旦保险3数据");
            logger.error(">> ScheduleController.sendXbb3 throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            return super.setResult(StatusCode.INTERNAL_SERVER_ERROR, "", null);
        }
        return super.setResult(StatusCode.OK, "", StatusCode.codeMsgMap.get(StatusCode.OK));
    }


    /**
     * 定时发送新旦保险3第三方数据(一个月一次)
     */
    @ResponseBody
    @RequestMapping("/sendXbb3Channel")
    public Result sendXbb3Channel() {
        try {
            asyncService.sendXbb3Channel();
        } catch (Exception e) {
            e.printStackTrace();
            String params = String.format("参数：error:%s",
                    "定时发送新旦保险3第三方数据");
            logger.error(">> ScheduleController.sendXbb3Channel throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            return super.setResult(StatusCode.INTERNAL_SERVER_ERROR, "", null);
        }
        return super.setResult(StatusCode.OK, "", StatusCode.codeMsgMap.get(StatusCode.OK));
    }


    /**
     * 定时发送新旦保险product数据
     */
    @ResponseBody
    @RequestMapping("/sendXbbProduct")
    public Result sendXbbProduct(@RequestParam(value = "amount", required = true) int amount) {
        try {
            asyncService.sendXbbProduct(amount);
        } catch (Exception e) {
            e.printStackTrace();
            String params = String.format("参数：error:%s",
                    "定时发送新旦保险product数据");
            logger.error(">> ScheduleController.sendXbbProduct throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            return super.setResult(StatusCode.INTERNAL_SERVER_ERROR, "", null);
        }
        return super.setResult(StatusCode.OK, "", StatusCode.codeMsgMap.get(StatusCode.OK));
    }

    /**
     * 定时发送拍拍贷旧数据
     */
    @ResponseBody
    @RequestMapping("/sendPpdsu2")
    public Result sendPpdsu2(@RequestParam(value = "amount", required = true) int amount) {
        try {
            asyncService.sendPpdsu2(amount);
        } catch (Exception e) {
            e.printStackTrace();
            String params = String.format("参数：error:%s",
                    "定时发送拍拍贷旧数据");
            logger.error(">> ScheduleController.sendXbb3Channel throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            return super.setResult(StatusCode.INTERNAL_SERVER_ERROR, "", null);
        }
        return super.setResult(StatusCode.OK, "", StatusCode.codeMsgMap.get(StatusCode.OK));
    }

    @ResponseBody
    @RequestMapping("/sendKaisen2")
    public Result sendKaisen2(@RequestParam(value = "amount") int amount) {
        try {
            asyncService.sendKaisen2(amount);
        } catch (Exception e) {
            e.printStackTrace();
            String params = String.format("参数：error:%s", "定时发送凯森2旧数据");
            logger.error(">> ScheduleController.sendXbb3Channel throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            return super.setResult(StatusCode.INTERNAL_SERVER_ERROR, "", null);
        }
        return super.setResult(StatusCode.OK, "", StatusCode.codeMsgMap.get(StatusCode.OK));
    }

    /**
     * 定时补发积压数据
     */
    /*@ResponseBody
    @RequestMapping("/scheduleZhudaiPush")
    public Result scheduleZhudaiPush() {
        try {
            asyncService.scheduleZhudaiPush();
        } catch (Exception e) {
            e.printStackTrace();
            String params = String.format("参数：error:%s",
                    "定时补发助贷网因限制数量而积压的数据");
            logger.error(">> ScheduleController.scheduleZhudaiPush throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            return super.setResult(StatusCode.INTERNAL_SERVER_ERROR, "", null);
        }
        return super.setResult(StatusCode.OK, "", StatusCode.codeMsgMap.get(StatusCode.OK));
    }
*/

    /**
     * 定时发送积压短信
     */
    @ResponseBody
    @RequestMapping("/sendStockSMS")
    public Result sendStockSMS() {
        try {
            asyncService.sendStockSMS();
        } catch (Exception e) {
            e.printStackTrace();
            String params = String.format("参数：error:%s",
                    "定时发送积压短信错误");
            logger.error(">> ScheduleController.sendStockSMS throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            return super.setResult(StatusCode.INTERNAL_SERVER_ERROR, "", null);
        }
        return super.setResult(StatusCode.OK, "", StatusCode.codeMsgMap.get(StatusCode.OK));

    }

    /**
     * 定时计算验证码转化率 低于70报警
     *
     * @return
     */
    @RequestMapping("/scheduleConversion")
    @ResponseBody
    public Result scheduleConversion() {
        BigDecimal conversionPercent = new BigDecimal(0);
        BigDecimal conversionPercent2 = new BigDecimal(0);
        BigDecimal finallyPercent = new BigDecimal(0);
        BigDecimal multiply = new BigDecimal(100);
        Integer percent;
        // 获取当前时间的前半小时和前一小时 并转为String类型
        long begin = System.currentTimeMillis() - 30 * 60 * 1000;
        long mobileBegin = System.currentTimeMillis() - 60 * 60 * 1000;
        long end = System.currentTimeMillis();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strBegin = df.format(begin);
        String strEnd = df.format(end);
        String strMobileBegin = df.format(mobileBegin);
        Map<String, Object> timeMap = new HashMap<>();
        Map<String, Object> countMap = new HashMap<>();
        timeMap.put("createTimeBegin", strBegin);
        timeMap.put("createTimeEnd", strEnd);
        countMap.put("createTimeBegin", strMobileBegin);
        countMap.put("createTimeEnd", strEnd);
        JSONObject jsonObject = new JSONObject();
        try {
            //查询验证码发送数，用户数，还有获取验证码超过三次的手机号
            Integer userCount = userService.getCountByTime(timeMap);
            Integer checkCodeCount = checkCodeService.getCount(timeMap);
            List<Map<String, Object>> mobileMap = checkCodeService.getMobileCount(countMap);
            if (userCount != null && userCount > 10 && checkCodeCount != null && checkCodeCount > 10) {
                BigDecimal bigDecimalUser = BigDecimal.valueOf(userCount);
                jsonObject.put("注册人数", userCount);
                BigDecimal bigDecimalCode = BigDecimal.valueOf(checkCodeCount);
                jsonObject.put("发送验证码数", checkCodeCount);
                // 计算转化率
                conversionPercent = bigDecimalUser.divide(bigDecimalCode, 4, RoundingMode.HALF_UP);
                conversionPercent2 = conversionPercent.multiply(multiply);
                finallyPercent = conversionPercent2.setScale(2);
                jsonObject.put("转化比例", finallyPercent + "%");
                BigDecimal resultPercent = new BigDecimal(70);
                percent = finallyPercent.compareTo(resultPercent);
                //编辑短信内容
                if (percent == -1) {
                    long now = System.currentTimeMillis();
                    Date nowDate = new Date(now);
                    DateFormat df1 = new SimpleDateFormat("HH:mm:ss");
                    String strNow = df1.format(nowDate);
                    jsonObject.put("当前时间", strNow);
                    String mailBody = "短信监控--" + strNow +
                            " 发生告警,成功率" + finallyPercent + "%,最近半小时内获取验证码"
                            + checkCodeCount + "条,注册人数" + userCount + "人<br/>" +
                            "最近一小时内获取验证码数大于三条的手机号统计:<br/>";
                    if (mobileMap.size() > 0) {
                        for (Map<String, Object> map : mobileMap) {
                            String mobile = map.get("mobile").toString();
                            String carrieroperator = JudgeOperator.matchNum(mobile);
                            mailBody += "手机号:" + mobile + "&nbsp;&nbsp;&nbsp;";
                            String totalcount = map.get("totalcount").toString();
                            mailBody += "次数:" + totalcount + "&nbsp;&nbsp;&nbsp;";
                            mailBody += "运营商:" + carrieroperator + "<br/>";
                        }
                    }
                    MailUtil.sendMail("15835132986@139.com", "短信告警", mailBody, true, null);
                    MailUtil.sendMail("15110299053@139.com", "短信告警", mailBody, true, null);
                    MailUtil.sendMail("15000020953@139.com", "短信告警", mailBody, true, null);

                }
            }
            return super.setResult(StatusCode.OK, jsonObject.toString(), "成功");
        } catch (Exception e) {
            e.printStackTrace();
            String params = String.format("参数：error:%s",
                    "定时计算验证码转化率接口报错");
            logger.error(">> ScheduleController.scheduleConversion throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            return super.setResult(StatusCode.INTERNAL_SERVER_ERROR, "", null);
        }

    }

    /**
     * 定时增加卡王贷渠道数据统计
     */
    @RequestMapping("scheduledAddKwChannel")
    @ResponseBody
    public Result scheduledAddKwChannel(@RequestParam(value = "jobDate", required = false) String jobDate) {
        Result result = new Result();
        try {
            scheduleService.scheduledAddKwChannel(jobDate);
        } catch (Exception e) {
            e.printStackTrace();
            String params = "";
            logger.error(">> ScheduleController.scheduledAddKwChannel throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            result.setCode(StatusCode.INTERNAL_SERVER_ERROR);
            return result;
        }
        result.setCode(StatusCode.OK);
        return result;
    }

    /**
     * 定时增加卡王贷产品点击数据
     */
    @RequestMapping("scheduledAddKwTrackEvent")
    @ResponseBody
    public Result scheduledAddKwTrackEvent() {
        Result result = new Result();
        try {
            scheduleService.scheduledAddKwTrackEvent();
        } catch (Exception e) {
            String params = "";
            logger.error(">> ScheduleController.scheduledAddKwTrackEvent throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            result.setCode(StatusCode.INTERNAL_SERVER_ERROR);
            return result;
        }
        result.setCode(StatusCode.OK);
        return result;
    }

    /**
     * 定时增加推送数据统计数据
     * 添加时间参数，如果定时任务失败后，可以通过传入时间来生成失败当天的数据
     */
    @RequestMapping("scheduledAddLimit")
    @ResponseBody
    public Result scheduledAddLimit(@RequestParam(value = "jobDate", required = false) String jobDate) {
        Result result = new Result();
        try {
            scheduleService.scheduledAddLimit(jobDate);
        } catch (Exception e) {
            e.printStackTrace();
            String params = "";
            logger.error(">> ScheduleController.scheduledAddLimit: throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            result.setCode(StatusCode.INTERNAL_SERVER_ERROR);
            return result;
        }
        result.setCode(StatusCode.OK);
        return result;
    }


    /**
     * 定时增加推送地区数量限制统计
     */
    @RequestMapping("scheduledAddAreaLimitData")
    @ResponseBody
    public Result scheduledAddAreaLimitData() {
        Result result = new Result();
        try {
            scheduleService.scheduledAddAreaLimitData();
        } catch (Exception e) {
            e.printStackTrace();
            String params = "";
            logger.error(">> ScheduleController.scheduledAddAreaLimitData: throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            result.setCode(StatusCode.INTERNAL_SERVER_ERROR);
            return result;
        }
        result.setCode(StatusCode.OK);
        return result;
    }

    /**
     * 接口限制数量还原
     */
    @RequestMapping("redisRestore")
    @ResponseBody
    public Result redisRestore() {
        Result result = new Result();
        Calendar calendar = Calendar.getInstance();
        Date logTimeBegin = DateUtils.getDayBeginTime(calendar.getTime());
        Date logTimeEnd = DateUtils.getDayEndTime(calendar.getTime());
        try {
            kwOperationLogService.addOperationLog("2", "接口限制数量还原", "redisRestore",
                    "定时任务", DateUtils.dateToStr(logTimeBegin), DateUtils.dateToStr(logTimeEnd), "redisRestore", 0,
                    null, null, null);
            kwInterfaceConfigService.restore();
        } catch (Exception e) {
            String params = String.format("参数：redisRestore:%s",
                    "接口限制数量还原错误");
            logger.error(">> ScheduleController.redisRestore throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            result.setCode(StatusCode.INTERNAL_SERVER_ERROR);
            return result;
        }
        result.setCode(StatusCode.OK);
        return result;
    }

    /**
     * 将数据导入lm表中
     */
    @ResponseBody
    @RequestMapping("moveData")
    public Result moveData(@RequestParam(value = "createTimeBegin", required = true) String createTimeBegin,
                           @RequestParam(value = "createTimeEnd", required = true) String createTimeEnd) {
        Result result = new Result();
        try {
            if (StringUtils.isBlank(createTimeBegin) || StringUtils.isBlank(createTimeEnd)) {
                return setResult(StatusCode.MISSING_ARGUMENT, null, StatusCode.codeMsgMap.get(StatusCode.MISSING_ARGUMENT));
            }
            //查出符合条件的用户
            Map<String, Object> resultMap = new HashMap<>();
            List<Map<String, Object>> resultList = new ArrayList<>();
            List<Map<String, Object>> userList = new ArrayList<>();
            Map<String, String> map = new HashMap<>();
            if (StringUtils.isNotBlank(createTimeBegin)) {
                map.put("createTimeBegin", createTimeBegin);
            }
            if (StringUtils.isNotBlank(createTimeEnd)) {
                map.put("createTimeEnd", createTimeEnd);
            }
            String url = ConfigUtil.getConfig("product.moveData.url");
            HttpUtil.HttpResult hr = null;
            hr = HttpUtil.doPostForm(url, map);
            String content = hr.getContent();
            JSONObject returnMsg = JSONObject.parseObject(content);
            JSONObject data = returnMsg.getJSONObject("data");
            resultList = (List<Map<String, Object>>) data.get("userInfo");
            for (Map<String, Object> userInfoMap : resultList) {
                String mobile = (String) userInfoMap.get("mobile");
                Integer count = lmUserBaseService.isExist(mobile);
                LmUser lmUser = new LmUser();
                lmUser.setCreateDate(new Date((Long) userInfoMap.get("createDate")));
                lmUser.setName((String) userInfoMap.get("name"));
                lmUser.setPhone((String) userInfoMap.get("mobile"));
                lmUser.setSex((Integer) userInfoMap.get("sex"));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String str = sdf.format(userInfoMap.get("birthday"));
                Date date = sdf.parse(str);
                lmUser.setBirthday(date);
                int age = 25;
                age = DateUtils.getAge(date);
                lmUser.setAge(age);
                lmUser.setAreaCode((Integer) userInfoMap.get("areaCode"));
                lmUser.setAreaName((String) userInfoMap.get("areaName"));
                lmUser.setPhoneAreaName((String) userInfoMap.get("mobileRegistration"));
                lmUser.setIp((String) userInfoMap.get("ip"));
                lmUser.setExpectAmount(new BigDecimal(userInfoMap.get("expectAmount").toString()));
                lmUser.setPolicy((Integer) userInfoMap.get("policy"));
                lmUser.setCredit((Integer) userInfoMap.get("credit"));
                lmUser.setHouse((Integer) userInfoMap.get("house"));
                lmUser.setCar((Integer) userInfoMap.get("car"));
                lmUser.setFund((Integer) userInfoMap.get("fund"));
                lmUser.setSocialSecurity((Integer) userInfoMap.get("socialSecurity"));
                lmUser.setOccupation((Integer) userInfoMap.get("occupation"));
                lmUser.setSalaryMethod((Integer) userInfoMap.get("salaryMethod"));
                lmUser.setWorkDuration((Integer) userInfoMap.get("workDuration"));
                lmUser.setSalary((Integer) userInfoMap.get("salary"));
                lmUser.setWxloan((Integer) userInfoMap.get("wxloan"));
                if (count != null && count == 1) {
                    lmUserService.update(lmUser);
                } else {
                    lmUserService.insert(lmUser);
                }
                LmUserBase lmUserBase = new LmUserBase();
                lmUserBase.setCreateDate(new Date((Long) userInfoMap.get("createDate")));
                lmUserBase.setChannelId((Integer) userInfoMap.get("channelId"));
                lmUserBase.setChannelCode((String) userInfoMap.get("channelCode"));
                lmUserBase.setChannelName((String) userInfoMap.get("channelName"));
                lmUserBase.setName((String) userInfoMap.get("name"));
                lmUserBase.setPhone((String) userInfoMap.get("mobile"));
                lmUserBase.setUserId(lmUser.getId());
                if (count != null && count == 1) {
                    lmUserBaseService.update(lmUserBase);
                } else {
                    lmUserBaseService.insert(lmUserBase);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(StatusCode.INTERNAL_SERVER_ERROR);
            return result;
        }
        result.setCode(StatusCode.OK);
        return result;
    }


    /**
     * 定时将上个月数据转移
     */
    @ResponseBody
    @RequestMapping("moveDataSchedule")
    public Result moveDataSchedule(@RequestBody String param) {
        Result result = new Result();
        List<Map<String, Object>> resultList = new ArrayList<>();
        JSONObject jsonObject = JSON.parseObject(param);
        resultList = (List<Map<String, Object>>) jsonObject.get("userInfo");
        System.out.println(resultList.toString());
        try {
            for (Map<String, Object> userInfoMap : resultList) {
                String mobile = (String) userInfoMap.get("mobile");
                Integer count = lmUserBaseService.isExist(mobile);
                LmUser lmUser = new LmUser();
                lmUser.setCreateDate(new Date((Long) userInfoMap.get("createDate")));
                lmUser.setName((String) userInfoMap.get("name"));
                lmUser.setPhone((String) userInfoMap.get("mobile"));
                lmUser.setSex((Integer) userInfoMap.get("sex"));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String str = sdf.format(userInfoMap.get("birthday"));
                Date date = sdf.parse(str);
                lmUser.setBirthday(date);
                int age = 25;
                age = DateUtils.getAge(date);
                lmUser.setAge(age);
                lmUser.setAreaCode((Integer) userInfoMap.get("areaCode"));
                lmUser.setAreaName((String) userInfoMap.get("areaName"));
                lmUser.setPhoneAreaName((String) userInfoMap.get("mobileRegistration"));
                lmUser.setIp((String) userInfoMap.get("ip"));
                lmUser.setExpectAmount(new BigDecimal(userInfoMap.get("expectAmount").toString()));
                lmUser.setPolicy((Integer) userInfoMap.get("policy"));
                lmUser.setCredit((Integer) userInfoMap.get("credit"));
                lmUser.setHouse((Integer) userInfoMap.get("house"));
                lmUser.setCar((Integer) userInfoMap.get("car"));
                lmUser.setFund((Integer) userInfoMap.get("fund"));
                lmUser.setSocialSecurity((Integer) userInfoMap.get("socialSecurity"));
                lmUser.setOccupation((Integer) userInfoMap.get("occupation"));
                lmUser.setSalaryMethod((Integer) userInfoMap.get("salaryMethod"));
                lmUser.setWorkDuration((Integer) userInfoMap.get("workDuration"));
                lmUser.setSalary((Integer) userInfoMap.get("salary"));
                lmUser.setWxloan((Integer) userInfoMap.get("wxloan"));
                if (count != null && count == 1) {
                    lmUserService.update(lmUser);
                } else {
                    lmUserService.insert(lmUser);
                }
                LmUserBase lmUserBase = new LmUserBase();
                lmUserBase.setCreateDate(new Date((Long) userInfoMap.get("createDate")));
                lmUserBase.setChannelId((Integer) userInfoMap.get("channelId"));
                lmUserBase.setChannelCode((String) userInfoMap.get("channelCode"));
                lmUserBase.setChannelName((String) userInfoMap.get("channelName"));
                lmUserBase.setName((String) userInfoMap.get("name"));
                lmUserBase.setPhone((String) userInfoMap.get("mobile"));
                lmUserBase.setUserId(lmUser.getId());
                if (count != null && count == 1) {
                    lmUserBaseService.update(lmUserBase);
                } else {
                    lmUserBaseService.insert(lmUserBase);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(StatusCode.INTERNAL_SERVER_ERROR);
            return result;
        }
        result.setCode(StatusCode.OK);
        return result;
    }

    /**
     * 每月统计数据推送情况
     */
    @ResponseBody
    @RequestMapping("statistics")
    public Result Statistics() {
        Result result = new Result();
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            //获取前月的第一天
            Calendar cal_1 = Calendar.getInstance();//获取当前日期
            cal_1.add(Calendar.MONTH, -1);
            cal_1.set(Calendar.DAY_OF_MONTH, 1);//设置为1号,当前日期既为本月第一天
            String dataDateBegin = format.format(DateUtils.getDayBeginTime(cal_1.getTime()));
            logger.info("-----1------firstDay:{}" + dataDateBegin);
            //获取当月第一天
            Calendar cale = Calendar.getInstance();
            cale.set(Calendar.DAY_OF_MONTH, 0);
            String dataDateEnd = format.format(DateUtils.getDayEndTime(cale.getTime()));
            logger.info("-----2------lastDay:{}" + dataDateEnd);
            kwStatisticInterfaceService.monthStatistics(dataDateBegin, dataDateEnd);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(StatusCode.INTERNAL_SERVER_ERROR);
            String params = "";
            logger.error(">> ScheduleController.Statistics throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            return result;
        }
        result.setCode(StatusCode.OK);
        return result;
    }

    /**
     * 每天5点 给微信活跃用户 发送消息
     */
    @RequestMapping("scheduledWxMsg")
    @ResponseBody
    public Result scheduledWxMsg() {
        Result result = new Result();
        try {
            asyncService.sendWxMsg();
        } catch (Exception e) {
            e.printStackTrace();
            String params = "";
            logger.error(">> ScheduleController.sendWxMsg: throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            result.setCode(StatusCode.INTERNAL_SERVER_ERROR);
            return result;
        }
        result.setCode(StatusCode.OK);
        return result;
    }

    /**
     * 定时发送熠巨接口
     */
    @RequestMapping("scheduledYiJu")
    @ResponseBody
    public Result scheduledYiJu() {
        Result result = new Result();
        try {
            asyncService.sendYiJu();
        } catch (Exception e) {
            e.printStackTrace();
            String params = "";
            logger.error(">> ScheduleController.scheduledYiJu: throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            result.setCode(StatusCode.INTERNAL_SERVER_ERROR);
            return result;
        }
        result.setCode(StatusCode.OK);
        return result;
    }

    /**
     * 定时发送熠巨方正接口
     */
    @RequestMapping("scheduledYiJuFz")
    @ResponseBody
    public Result scheduledYiJuFz() {
        Result result = new Result();
        try {
            asyncService.sendYiJuFz();
        } catch (Exception e) {
            e.printStackTrace();
            String params = "";
            logger.error(">> ScheduleController.scheduledYiJuFz: throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            result.setCode(StatusCode.INTERNAL_SERVER_ERROR);
            return result;
        }
        result.setCode(StatusCode.OK);
        return result;
    }

    /**
     * 每天统计当月数据推送情况
     */

    @RequestMapping("monthStatistics")
    @ResponseBody
    public Result monthStatistics() {
        Result result = new Result();
        try {
            Date currentDate = new Date();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            //获取当月的第一天
            Calendar cal = Calendar.getInstance();//获取当前日期;
            cal.set(Calendar.DAY_OF_MONTH, 1);//设置为1号,当前日期既为本月第一天
            String dataDateBegin = format.format(DateUtils.getDayBeginTime(cal.getTime()));
            String monthTime = format.format(new Date());
            if (dataDateBegin.equals(monthTime)) {
                cal.add(Calendar.MONTH, -1);
                cal.set(Calendar.DAY_OF_MONTH, 1);
                dataDateBegin = format.format(DateUtils.getDayBeginTime(cal.getTime()));
            }
            logger.info("-----1------firstDay:{}" + dataDateBegin);
            //获取当天的前一天
            Date createTimeEnd = org.apache.commons.lang3.time.DateUtils.addDays(currentDate, -1);
            String dataDateEnd = format.format(createTimeEnd);
            logger.info("-----2------lastDay:{}" + dataDateEnd);
            kwStatisticInterfaceService.monthStatistics(dataDateBegin, dataDateEnd);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(StatusCode.INTERNAL_SERVER_ERROR);
            String params = "";
            logger.error(">> ScheduleController.Statistics throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            return result;
        }
        result.setCode(StatusCode.OK);
        return result;
    }

}
